package com.raos.fastdfs.controller;

import com.raos.fastdfs.domain.FastDfsFile;
import com.raos.fastdfs.utils.FastDFSClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件服务接口
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2022/11/5 9:41
 */
@Slf4j
@RequestMapping("/fileManage")
@RestController
public class FileController {

    @Value("${file.url}")
    private String fileUrl;

    @PostMapping("/upload")
    public String upload(MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                //1.获取到文件本身的字节数组
                byte[] content = file.getBytes();
                //2.获取文件的名称 --》获取图片的后缀
                String name = file.getOriginalFilename();
                //3.上传到fastdfs上
                //[0] =group1
                //[1] =M00/00/00/wKjThF-qeNyATiVHAAAl8vdCW2Y824.png
                String[] upload = FastDFSClient.upload(new FastDfsFile(
                        name,
                        content,
                        StringUtils.getFilenameExtension(name)
                ));
                //4.拼接Ulr
                // http://192.168.211.132:8080/group1/M00/00/00/wKjThF-qeNyATiVHAAAl8vdCW2Y824.png
                String realPath = fileUrl + "/" + upload[0] + "/" + upload[1];
                log.info("上传文件的访问url=[{}]", realPath);
                //5.返回url给页面
                return realPath;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

}
